package com.yanglei.demo.framework.core.handler;

import cn.hutool.http.HttpStatus;
import com.yanglei.demo.client.dto.CommonResult;
import com.yanglei.demo.framework.core.util.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问一个需要人在的URL资源，但是此时自己尚未认证（登录）的情况下，返回错误码，从而使前端能重定向到登录页
 */
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.debug("[commence][访问 URL({}) 时，没有登录]", request.getRequestURI(), e);
        CommonResult<Object> result = new CommonResult<>();
        result.setCode(HttpStatus.HTTP_UNAUTHORIZED);
        result.setMsg("账号未登录");
        ServletUtils.writeJSON(response,result);
    }
}
